<template>
  <div id="app" class="appclass">
    <!-- 主内容区域 -->
    <div class="main-content" :class="{ 'has-player': currentSong }">
      <!-- 根据当前页面显示不同组件 -->
      <PlayerPage 
        v-if="currentPage === 'player'" 
        :song="currentSong"
        :isPlaying="isPlaying"
        :currentTime="currentTime"
        :duration="duration"
        :play-mode="playMode"
        :lyrics="lyrics"
        @toggle-play="togglePlay"
        @prev-song="prevSong"
        @next-song="nextSong"
        @back="goBack"
        @play-mode="switchMode"
        @set-current-time="setCurrentTime"
      />
      
      <MenuPage 
        v-else-if="currentPage === 'menu'"
        @navigate="navigateTo"
        @close="goBack"
      />
      
      <SearchPage 
        v-else-if="currentPage === 'search'"
        @back="goBack"
      />
      
      <AboutPage 
        v-else-if="currentPage === 'about'"
        @back="goBack"
      />
      
      <PlaylistPage 
        v-else-if="currentPage === 'playlist'"
        @select-playlist="selectPlaylist"
        @back="goBack"
      />
      
      <SongListPage 
        v-else-if="currentPage === 'songlist'"
        :selected-playlist="selectedPlaylist"
        @select-song="selectSong"
        @back="goBack"
        @song-list="updateSongList"
      />
      
      <!-- 默认首页 -->
      <div v-else class="home-page">
        <div class="home-header">
          <h1>音乐播放器</h1>
          <button class="menu-btn" @click="openMenu">
            <i class="fas fa-bars"></i>
          </button>
        </div>
        <div class="home-content">
          <p>点击底部播放栏或菜单开始播放音乐</p>
        </div>
      </div>
    </div>
    
    <!-- 底部播放控制栏 -->
    <BottomPlayer 
      v-if="currentPage !== 'player'"
      :song="currentSong"
      :is-playing="isPlaying"
      :current-time="currentTime"
      :duration="duration"
      @toggle-play="togglePlay"
      @open-player="openPlayer"
    />
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import BottomPlayer from '../components/BottomPlayer.vue'
import PlayerPage from '../components/PlayerPage.vue'
import MenuPage from '../components/MenuPage.vue'
import SearchPage from '../components/SearchPage.vue'
import PlaylistPage from '../components/PlaylistPage.vue'
import SongListPage from '../components/SongListPage.vue'
import AboutPage from '../components/AboutPage.vue'
import { apiService } from '../utils/http'

export default {
  name: 'MusicMenuPage',
  components: {
    BottomPlayer,
    PlayerPage,
    MenuPage,
    SearchPage,
    PlaylistPage,
    SongListPage,
    AboutPage
  },
  setup() {
    // 当前播放的歌曲
    const currentSong = ref(null)
    // 是否正在播放
    const isPlaying = ref(false)
    // 当前播放时间
    const currentTime = ref(0)
    // 歌曲总时长
    const duration = ref(0)
    // 当前页面
    const currentPage = ref('playlist')
    // 选中的歌单信息（包含 play 和 nickname）
    const selectedPlaylist = ref({ play: '', nickname: '' })
    // 音频对象
    const audio = ref(null)
    // 当前播放中的歌单
    const songs = ref([])
    // 当前播放模式
    const playMode = ref('sequential')
    // 当前随机播放的歌单列表
    const random_songs = ref([])
    // 当前播放次数是否已记录
    const isAddPlayCount = ref(false)
    // 歌词
    const lyrics = ref('')
    
    // 初始化音频
    onMounted(() => {
      audio.value = new Audio()
      
      audio.value.addEventListener('loadedmetadata', () => {
        duration.value = audio.value.duration
      })
      
      audio.value.addEventListener('timeupdate', () => {
        currentTime.value = audio.value.currentTime
        if (!isAddPlayCount.value && (currentTime.value / duration.value) >= 0.55) {
          apiService.post('/PlayCountAdd', {music: currentSong.value.id})
          isAddPlayCount.value = true
        }
      })
      
      audio.value.addEventListener('ended', () => {
        isAddPlayCount.value = false
        if (playMode.value == 'single') {
          playSong(currentSong.value)    // 单曲循环播放
          return
        } else if (playMode.value == 'disabled') {
          isPlaying.value = false
          return   // 禁用歌曲切换
        } else if (playMode.value == 'sequential') {  // 顺序播放
          const currentIndex = songs.value.findIndex(song => song.id === currentSong.value.id)
          if (currentIndex == songs.value.length - 1) {
            isPlaying.value = false
            return   // 播放到最后一首则结束
          }
        }
        nextSong()
      })
    })
    
    // 播放/暂停切换
    const togglePlay = () => {
      if (!currentSong.value) return
      
      if (isPlaying.value) {
        audio.value.pause()
      } else {
        audio.value.play()
      }
      isPlaying.value = !isPlaying.value
    }
    
    // 设置播放时间
    const setCurrentTime = (time) => {
      if (!currentSong.value || !audio.value) return
      
      // 确保时间在有效范围内
      const newTime = Math.max(0, Math.min(time, duration.value))
      audio.value.currentTime = newTime
      currentTime.value = newTime
    }
    
    // 获取歌词
    const fetchLyrics = async (songId) => {
      try {
        const res = await apiService.post('/LyricsQuery', {music: songId})
        lyrics.value = res.data.lyrics || ''
      } catch (error) {
        console.error('获取歌词失败:', error)
        lyrics.value = ''
      }
    }
    
    // 播放指定歌曲
    const playSong = async (song) => {
      try {
        const res = fetch('/audio' + song.url, {
          method: 'GET',
        }).then(response => {
          if (!response.ok) {
              throw new Error('Network response was not ok');
          }
          return response.blob(); // 获取二进制数据
        }).then(blob => {
          // 创建一个URL对象指向这个blob，这样就可以设置到audio元素的src属性上
          const audioUrl = URL.createObjectURL(blob);
          audio.value.src = audioUrl;;
          audio.value.play();  // 播放音频
        }).catch(error => {
          console.error('There has been a problem with your fetch operation:', error);
        });
      } catch (error) {
        console.error('歌曲播放失败:', error)
      }
      
      currentSong.value = song
      audio.value.src = song.url
      audio.value.play()
      isPlaying.value = true
      currentPage.value = 'player'

      // 获取歌词
      await fetchLyrics(song.id)
    }

    // 洗牌算法，打乱数组
    const shuffleArray = (array) => {
      const newArray = JSON.parse(JSON.stringify(array));
      for (let i = newArray.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1)); // 随机索引
        [newArray[i], newArray[j]] = [newArray[j], newArray[i]]; // 交换元素
      }
      return newArray;
    }

    // 更新当前播放模式
    const switchMode = (data) => {
      playMode.value = data
      if (data == 'random') {
        random_songs.value = shuffleArray(songs.value)
      }
    }
    
    // 上一首
    const prevSong = () => {
      if (!currentSong.value) return
      
      if (playMode.value == 'random') {  // 随机播放
        const currentIndex = random_songs.value.findIndex(song => song.id === currentSong.value.id)
        const nextIndex = (currentIndex - 1) % random_songs.value.length
        playSong(random_songs.value[nextIndex])
        if (currentIndex == random_songs.value.length - 1) {
          random_songs.value = shuffleArray(songs.value)
        }
      } else {  // 列表循环播放
        const currentIndex = songs.value.findIndex(song => song.id === currentSong.value.id)
        const prevIndex = (currentIndex - 1 + songs.value.length) % songs.value.length
        playSong(songs.value[prevIndex])
      }
    }
    
    // 下一首
    const nextSong = () => {
      if (!currentSong.value) return

      if (playMode.value == 'random') {  // 随机播放
        const currentIndex = random_songs.value.findIndex(song => song.id === currentSong.value.id)
        const nextIndex = (currentIndex + 1) % random_songs.value.length
        playSong(random_songs.value[nextIndex])
        if (currentIndex == random_songs.value.length - 1) {
          random_songs.value = shuffleArray(songs.value)
        }
      } else {  // 列表循环播放
        const currentIndex = songs.value.findIndex(song => song.id === currentSong.value.id)
        const nextIndex = (currentIndex + 1) % songs.value.length
        playSong(songs.value[nextIndex])
      }
    }
    
    // 打开播放页面
    const openPlayer = () => {
      if (currentSong.value) {
        currentPage.value = 'player'
      }
    }
    
    // 打开菜单
    const openMenu = () => {
      currentPage.value = 'menu'
    }
    
    // 页面导航
    const navigateTo = (page) => {
      currentPage.value = page
    }
    
    // 选择歌单 - 现在传递完整的歌单对象
    const selectPlaylist = (playlist) => {
      selectedPlaylist.value = playlist
      currentPage.value = 'songlist'
    }
    
    // 选择歌曲
    const selectSong = (song) => {
      playSong(song)
    }

    // 更新播放中的歌单
    const updateSongList = (data) => {
      songs.value = data
    }
    
    // 返回上一页
    const goBack = () => {
      if (currentPage.value === 'player') {
        currentPage.value = 'songlist'
      } else if (currentPage.value === 'songlist') {
        currentPage.value = 'playlist'
      } else if (currentPage.value === 'playlist') {
        currentPage.value = 'menu'
      } else if (currentPage.value === 'search') {
        currentPage.value = 'menu'
      } else if (currentPage.value === 'about') {
        currentPage.value = 'menu'
      } else {
        currentPage.value = ''
      }
    }
    
    return {
      currentSong,
      isPlaying,
      currentTime,
      duration,
      currentPage,
      selectedPlaylist,
      playMode,
      lyrics,
      togglePlay,
      playSong,
      prevSong,
      nextSong,
      openPlayer,
      openMenu,
      navigateTo,
      selectPlaylist,
      selectSong,
      goBack,
      updateSongList,
      switchMode,
      setCurrentTime  // 返回设置播放时间的方法
    }
  }
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}

body {
  /* font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; */
  background-color: #f5f5f5;
  /* background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%); */
  color: #333;
  overflow-x: hidden;
}

.appclass {
  position: relative;
  max-width: 400px;
  margin: 0 auto;
  min-height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
  padding-bottom: 80px; /* 为底部播放栏留出空间 */
}

.main-content {
  min-height: calc(100vh - 80px);
  padding: 0;
  transition: all 0.3s ease;
}

.home-page {
  padding: 20px;
}

.home-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #e0e0e0;
}

.home-header h1 {
  color: #c62828;
  font-size: 24px;
}

.menu-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #c62828;
  cursor: pointer;
  padding: 8px;
}

.home-content {
  padding: 40px 20px;
  text-align: center;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .home-header h1 {
    font-size: 20px;
  }
}
</style>
